package simulator.robot;

import java.util.ArrayList;

import lejos.robotics.navigation.DifferentialPilot;
import simulator.labyrinth.BarCode;
import simulator.position.Position;
import Robot.SensorColour;

public class BarCodeScanner {
	public final static int BLACK_BROWN = 387;
	public final static int BROWN_WHITE = 484;
	private Simulator sim;
	
	private SimulatorListener listener;
	
	public BarCodeScanner(Simulator simulator,SimulatorListener listener){
		this.sim = simulator;
		this.listener = listener;
	}
	
	
	private SensorColour getLightColour()
	{
		if(listener.getLightValue() <= BLACK_BROWN)
			return SensorColour.BLACK;
		if(listener.getLightValue() <= BROWN_WHITE)
			return SensorColour.BROWN;
		else
			return SensorColour.WHITE;
	}
	
	
	
	public BarCode scanBarcode(){
		return createBarcode(scanPoints());
	}
	
	public BarCode createBarcode(ArrayList<SensorColour> points){
		int result = 0;
		for(int i = 0; i < points.size(); i++)
			if(points.get(i) == SensorColour.BROWN)
				points.remove(i);
		
		double interval = points.size()/4.0;
		int i = points.size()/8;
		int modulo = 1;
		while (i <= 7*points.size()/8){
			double line = 0;
			while (i <= interval) {
			    if (points.get(i)==SensorColour.WHITE)
			        line++;
			    i++;
			}
			double colour = line/(points.size()/8.0);
			if (Double.compare(colour, 0.5) > 0)
				result = result+modulo;
			interval = interval + points.size()/8.0;
			modulo *= 2;
		}
//		System.out.println(result+"/"+BarCode.calculateInverseNumber(result)+"//");
		return new BarCode(result,new Position(sim.getPosition().getX(),sim.getPosition().getY(),(sim.getPosition().getOrientation()+90)/180));
	}
	
	public ArrayList<SensorColour> scanPoints(){
		ArrayList<SensorColour> list = new ArrayList<SensorColour>();
		sim.forward();
		while (getLightColour() == SensorColour.BROWN)
			try {
				Thread.sleep(10);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
		boolean lus = true;
		while (lus) {
			list.add(getLightColour());
			if(list.size() >=3) {
				if(list.get(list.size()-1)==list.get(list.size()-2)&&list.get(list.size()-3)==list.get(list.size()-2)
						&&list.get(list.size()-2)==SensorColour.BROWN){
					sim.stop();
					lus = false;
				}
			}
				
			try {
				Thread.sleep(1000 / ((long) sim.getTravelSpeed() * 4));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		return list;
		
	
	}
	
}


